//
//  TSAccountViewController.swift
//  TSProfitProject
//
//  Created by TMS on 2019/11/6.
//  Copyright © 2019 TMS. All rights reserved.
//

import UIKit
import MJRefresh


extension NSNotification.Name {
    public static let TSLogoutNotification = Notification.Name("TSLogoutNotification")
}

class TSAccountViewController: TSBaseViewController {

    private var isFirstLoad = true
    
    private var tableController : TSBaseTableViewController!
    private var dataSource : [TSNormalCellModel] = []
    
    private var updateLink : String? = nil
    
    lazy var headerInfoView : TSAccountInfoView = {
        let headerView = TSAccountInfoView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 178))
        return headerView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.navigationController?.delegate = self;
        
        handleDatas()
        configViews()
        creatCustomNavi()
        
        requestUpdateLink()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        requestUserInfo(showHud: isFirstLoad)
        if isFirstLoad == true {
            isFirstLoad = false
        }
    }
    
    @objc func logoutAction() {
        
        NotificationCenter.default.post(name: .TSLogoutNotification, object: nil)
        
        TSLoginManager.shared.clearUserInfo()
        UIApplication.shared.keyWindow?.rootViewController = TSLoginViewController()
    }
    
    @objc func refreshDatas() {
        requestUserInfo(showHud: false)
        requestUpdateLink()
    }
    
    func getRecordType(title:String) -> TSRecordType {
        switch title {
//        case "中奖记录":
//            return TSRecordType.investType
        case "投注记录":
            return TSRecordType.investType
        case "充值记录":
            return TSRecordType.rechargeType
        case "提现记录":
            return TSRecordType.withdrawType
        case "账变明细":
            return TSRecordType.conversionType
        default:
            return TSRecordType.unknownType
        }
    }
    
    deinit {
        self.navigationController?.delegate = nil
    }

}

extension TSAccountViewController : TSAccountTableViewCellDelegate {
    
    func didClickItem(idx: Int) {
        
        var vc : TSBaseViewController?
        let model = dataSource[idx]
        
        switch idx {
        case 0, 1, 2, 3:
            let recordVc = TSAccountRecordViewController()
            recordVc.recordType = getRecordType(title: model.title)
            vc = recordVc
        case 4:
            vc = TSAccountAddVipViewController()
        case 5:
            vc = TSMyTeamViewController()
        case 6:
            vc = TSCardListViewController()
        case 7:
            vc = TSSecuritySettingViewController()
        case 8:
            if self.updateLink != nil {
                UIApplication.shared.open(URL(string: self.updateLink!)!, options: [:], completionHandler: nil)
            } else {
                CBToast.showToastAction(message: "获取版本信息失败，请稍后再试")
            }
        case 9:
            logoutAction()
            return
        default:
            return
        }
        
        if vc != nil {
            self.navigationController?.pushViewController(vc!, animated: true)
        }
    }
}

// MARK: - UITableViewDelegate
extension TSAccountViewController : UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        let itemH : CGFloat = 48
        let lineSpacing : CGFloat = 18

        return dataSource.count == 0 ? 0 : (20 + 3*itemH + 2*lineSpacing);
    }
    
}

// MARK: - UITableViewDataSource
extension TSAccountViewController : UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        var cell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(TSAccountTableViewCell.self)) as? TSAccountTableViewCell
        if cell == nil {
            cell = TSAccountTableViewCell(style: .default, reuseIdentifier: NSStringFromClass(TSAccountTableViewCell.self))
        }
        
        cell?.delegate = self
        
        cell?.setupCell(array: dataSource)
        
        return cell!
    }
    
}

// MARK: - TSAccountSectionHeaderViewDelegate
extension TSAccountViewController : TSAccountSectionHeaderViewDelegate {
    func didClickItem(title: String) {
        print(title)
        switch title {
        case "充值":
            navigationController?.pushViewController(TSRechargeViewController(), animated: true)
        case "提现":
            navigationController?.pushViewController(TSWithDrawViewController(), animated: true)
        case "额度转换":
            navigationController?.pushViewController(TSLimitConvertViewController(), animated: true)
        case "公告":
            navigationController?.pushViewController(TSNoticeViewController(), animated: true)
        default: break
        }
    }
    
}

// MARK: - Network Request
extension TSAccountViewController {

    func requestUserInfo(showHud:Bool) {
        
        if showHud {
            CBToast.showToastAction()
        }
        TSNetworkManager.request(TMSNetworkTools.getUserInfo, showHUD: showHud, success: { (data) in
            
            CBToast.hiddenToastAction()
            self.tableController.tableView.mj_header.endRefreshing()
            
            let responseDic = data as? NSDictionary
            var model = TSLoginModel.deserialize(from: responseDic)!
            model.token = TSLoginManager.shared.token
            model.user_id = TSLoginManager.shared.user_id
            TSLoginManager.shared.setUserModel(model: model)
            
            self.headerInfoView.refreshHeaaerView()
                        
        }) { (error) in
            CBToast.hiddenToastAction()
            self.tableController.tableView.mj_header.endRefreshing()
        }
    }
    
    func requestUpdateLink() {
        TSNetworkManager.request(TMSNetworkTools.getUpdateLink, showHUD: false, success: { (data) in
            
            self.updateLink = data as? String
            
        }) { (error) in
            
        }
    }
}

// MARK: - Initialize
extension TSAccountViewController {
    
    func creatCustomNavi() {
        
        let customStatus = UIView.init()
        customStatus.backgroundColor = BASE_RED_COLOR
        self.view.addSubview(customStatus)
        customStatus.snp.makeConstraints { (make) in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(STATUSBAR_HEIGHT)
        }
        
        let customNavi = UIView.init()
        customNavi.backgroundColor = BASE_RED_COLOR
        self.view.addSubview(customNavi)
        customNavi.snp.makeConstraints { (make) in
            make.left.right.equalTo(customStatus)
            make.top.equalTo(customStatus.snp.bottom)
            make.height.equalTo(NAVIGATIONBAR_HEIGHT)
        }
        
        let titleLabel = UILabel.init()
        titleLabel.text = "我的"
        titleLabel.textColor = WHITE_COLOR
        titleLabel.font = UIFont.boldSystemFont(ofSize: 17)
        customNavi.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.center.equalToSuperview()
        }
    }
    
    func configViews() {
        
        tableController = TSBaseTableViewController.init(style: .plain)
        tableController.shouldDisplayEmptyAlert = false
        tableController.tableView.backgroundColor = WHITE_COLOR
        tableController.tableView.delegate = self
        tableController.tableView.dataSource = self
        tableController.tableView.showsVerticalScrollIndicator = false
        tableController.tableView.separatorStyle = .none
        tableController.tableView.tableHeaderView = headerInfoView
        view.addSubview(tableController.tableView)
        tableController.tableView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(T_NAVBARHEIGHT)
            make.bottom.equalToSuperview().inset(T_TABBARHEIGHT)
        }
    
        tableController.tableView.mj_header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(refreshDatas))
    }
    
    func handleDatas() {
        
        let titleArray = ["投注记录", "充值记录", "提现记录", "账变明细", "增加会员", "我的团队", "银行卡", "安全设置", "更新版本", "退出登录"]
        for index in 0..<titleArray.count {
            let model = TSNormalCellModel.init(title: titleArray[index], value: "", textColor: "#363636", font: UIFont.systemFont(ofSize: 13, weight: .medium), imgName: "account_item\(index)")
            dataSource.append(model)
        }
    }
}

// MARK: - UINavigationControllerDelegate
extension TSAccountViewController : UINavigationControllerDelegate {
    func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
        let isShowHomePage = viewController.isKind(of: TSAccountViewController.self)
        self.navigationController?.setNavigationBarHidden(isShowHomePage, animated: false)
    }
}
